package com.jams.goodox.activity.serve;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;

import com.hangzhou.jin.customview.LoadView;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.adapter.PictureGroupAdapter;
import com.jams.goodox.constant.AppConfig;
import com.jams.goodox.entity.Neighborhood;
import com.jams.goodox.entity.resp.PersonalRentingResp;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.LifeService;
import com.jams.goodox.utils.CollectionUtils;
import com.jams.goodox.utils.DelayUtils;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.UserUtils;
import com.jams.goodox.widget.BlankClickGridView;
import com.jams.goodox.widget.RefreshRecyclerView;
import com.jams.goodox.widget.mannger.RefreshLinearLayoutManager;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;
import com.jams.library.listener.OnRecycleItemClickListener;
import com.jams.library.widget.RecyclerDivider;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import retrofit2.Call;

/**
 * 个人发布的租房列表页
 * <p>
 * create by 顾佳佳 on 2017/05/05
 */
public class PersonalRentingActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.empty_view)
    LoadView emptyView;
    @Bind(R.id.rcv_innings)
    RefreshRecyclerView rcvInnings;
    @Bind(R.id.srl_innings)
    SwipeRefreshLayout srl;

    private List<Neighborhood> dataList;
    private int curPage;
    private int clickItemPosition = -1;//用来记录点击的标记，详情页删除回调局部刷新

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal_re;
    }

    @Override
    protected void init() {
        srl.setOnRefreshListener(this);
        curPage = 1;
        dataList = new ArrayList<>();
        StyleUtil.titleBackKeyWithRightIconListener(this, getString(R.string.personal_renting), R.mipmap.title_bar_add, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PersonalRentingActivity.this, RentingPublishActivity.class);
                startActivityForResult(intent, 1991);
            }
        });
        rcvInnings.setLayoutManager(new RefreshLinearLayoutManager(this));
        rcvInnings.setHasFixedSize(true);
        rcvInnings.setAdapter(new RecycleCommonAdapter<Neighborhood>(this, dataList, R.layout.personal_renting_item) {
            @Override
            public void convert(RecycleCommonViewHolder helper, Neighborhood item, int position) {
                setData(helper, item, position);
            }
        });
        rcvInnings.setLoadDataListener(new RefreshRecyclerView.LoadDataListener() {
            @Override
            public void onLoadMore() {
                // 开启线加载更多数据
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        getRentingData();
                    }
                });

            }
        });
        rcvInnings.addItemDecoration(new RecyclerDivider(
                mContext, LinearLayoutManager.VERTICAL, 3, ContextCompat.getColor(this, R.color.shallow_divider)));
        onRefresh();
    }

    //获取转租列表
    private void getRentingData() {
        enqueue(createCallService(LifeService.class).getPersonalRentingList(SePref.getCommunityId(), curPage, AppConfig.PagSize), new RetrofitCallbackListener<PersonalRentingResp>() {
            @Override
            public void onSuccess(Call<PersonalRentingResp> call, PersonalRentingResp result) {
                rcvInnings.loadMoreComplete();
                srl.setRefreshing(false);
                if (result.getData() != null) {
                    if (curPage == 1) {
                        dataList.clear();
                    }
                    if (result.getData().getPageInfo() == null) {
                        rcvInnings.setCanLoadMore(false);
                    } else {
                        rcvInnings.setCanLoadMore(result.getData().getPageInfo().isHasMore());
                    }
                    dataList.addAll(result.getData().getResultList());
                    curPage++;
                    rcvInnings.notifyData();
                }
                if (!CollectionUtils.hasData(dataList)) {
                    emptyView.loadCompleteNoData(R.mipmap.holder_no_room,"暂无房源");
                } else {
                    emptyView.loadComplete();
                }
            }

            @Override
            public void onError(String msg) {
                rcvInnings.loadMoreComplete();
                srl.setRefreshing(false);
                if (!CollectionUtils.hasData(dataList)) {
                    emptyView.loadCompleteNoData(R.mipmap.holder_no_room,"暂无房源");
                } else {
                    emptyView.loadComplete();
                }
            }
        });
    }

    //设置item数据
    private void setData(RecycleCommonViewHolder helper,final Neighborhood item,final int position) {
        helper.setSimpleDraweeView(R.id.sdv_innings_portrait_item, item.getUserSimple().getPortraitUrl())
                .setText(R.id.tv_innings_name_item, item.getUserSimple().getNickName())
                .setText(R.id.tv_innings_type_item, item.getLabel())
                .setText(R.id.tv_innings_content, item.getTopicContent())
                .setText(R.id.tv_innings_list_publish_time, item.getIntime())
                .setText(R.id.tv_good_item, item.getTopicPraise() + "")
                .setText(R.id.tv_comment_item, item.getTopicMsgcnt() + "")
                .setOnItemClickListener(new OnRecycleItemClickListener() {
                    @Override
                    public void itemClick() {
                        gotoDetailPage(item,position);
                    }
                });
        UserUtils.setSexImage(item.getUserSimple(),(ImageView)helper.getView(R.id.iv_sex));
        setImageList((BlankClickGridView) helper.getView(R.id.gv_innings_item), item, position);
    }

    //设置图片
    private void setImageList(BlankClickGridView gridView, final Neighborhood item, final int mPosition) {
        gridView.setVisibility(View.VISIBLE);
        PictureGroupAdapter gridAdapter = new PictureGroupAdapter(this, item.getAnnexs(), 83, 3);
        gridView.setAdapter(gridAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                gotoDetailPage(item, mPosition);
            }
        });
        gridView.setOnTouchBlankPositionListener(new BlankClickGridView.OnTouchBlankPositionListener() {
            @Override
            public void onTouchBlank(MotionEvent event) {
                gotoDetailPage(item, mPosition);
            }
        });
    }

    //跳转到详情页
    private void gotoDetailPage(Neighborhood item, int position) {
        clickItemPosition = position;
        Intent intent = new Intent(this, PersonalRentingDetailActivity.class);
        intent.putExtra(PersonalRentingDetailActivity.ID, item.getId());
        startActivityForResult(intent, 1991);
    }

    @Override
    public void onRefresh() {
        DelayUtils.doAfterDelay(100, new DelayUtils.DelayDoListener() {
            @Override
            public void doAction() {
                srl.setRefreshing(true);
                curPage = 1;
                getRentingData();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1991) {
            switch (resultCode){
                case 1992://发布成功
                    onRefresh();
                    break;
                case 1993://删除成功
                    dataList.remove(clickItemPosition);
                    if (!CollectionUtils.hasData(dataList)) {
                        emptyView.loadCompleteNoData(R.mipmap.holder_no_room,"暂无房源");
                    } else {
                        emptyView.loadComplete();
                    }
                    rcvInnings.notifyData();
                    break;
            }
        }
    }
}
